<template>
  <div class="admin-login-container">
    <div class="login-box">
      <div class="login-header">
        <h1>管理员登录</h1>
        <p>食速达外卖平台 - 管理后台</p>
      </div>

      <el-tabs v-model="loginType" class="login-tabs">
        <!-- 密码登录 -->
        <el-tab-pane label="密码登录" name="password">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" class="login-form">
            <el-form-item prop="phone">
              <el-input 
                v-model="passwordForm.phone" 
                placeholder="请输入手机号" 
                prefix-icon="Phone"
                size="large">
              </el-input>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input 
                v-model="passwordForm.password" 
                type="password" 
                placeholder="请输入密码" 
                prefix-icon="Lock"
                size="large"
                show-password>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button 
                type="primary" 
                size="large" 
                class="login-btn" 
                @click="handlePasswordLogin"
                :loading="loading">
                登 录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 验证码登录 -->
        <el-tab-pane label="验证码登录" name="code">
          <el-form :model="codeForm" :rules="codeRules" ref="codeFormRef" class="login-form">
            <el-form-item prop="phone">
              <el-input 
                v-model="codeForm.phone" 
                placeholder="请输入手机号" 
                prefix-icon="Phone"
                size="large">
              </el-input>
            </el-form-item>
            
            <el-form-item prop="code">
              <div class="code-input-group">
                <el-input 
                  v-model="codeForm.code" 
                  placeholder="请输入验证码" 
                  prefix-icon="Message"
                  size="large"
                  style="flex: 1;">
                </el-input>
                <el-button 
                  size="large" 
                  :disabled="countdown > 0"
                  @click="handleGetCode">
                  {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button 
                type="primary" 
                size="large" 
                class="login-btn" 
                @click="handleCodeLogin"
                :loading="loading">
                登 录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div class="login-tip">
        <el-icon><Warning /></el-icon>
        <span>仅限管理员登录</span>
      </div>
    </div>

    <!-- 验证码弹窗 -->
    <el-dialog v-model="codeDialogVisible" title="验证码" width="400px">
      <div class="code-dialog-content">
        <p class="code-number">{{ verifyCode }}</p>
        <p class="code-tip">请在登录框中输入此验证码</p>
      </div>
      <template #footer>
        <el-button @click="codeDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="autoFillCode">自动填充</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { userApis } from '@/assets/apis/UserApis'
import { userInfoStore } from '@/assets/userStore/userStore'

const router = useRouter()
const userStore = userInfoStore()

// 登录方式
const loginType = ref('password')
const loading = ref(false)

// 密码登录表单
const passwordForm = reactive({
  phone: '',
  password: ''
})

const passwordRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const passwordFormRef = ref()

// 验证码登录表单
const codeForm = reactive({
  phone: '',
  code: ''
})

const codeRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const codeFormRef = ref()

// 验证码相关
const countdown = ref(0)
const codeDialogVisible = ref(false)
const verifyCode = ref('')
let countdownTimer: any = null

// 密码登录
const handlePasswordLogin = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const user = await userApis.loginByPassword(passwordForm.phone, passwordForm.password)
        
        // 验证是否为管理员
        if (!user.is_admin) {
          ElMessage.error('该账号不是管理员，无法登录管理后台')
          return
        }
        
        // 保存用户信息
        userStore.update(user.id, user.username, user.phone, user.head_portrait, user.password)
        
        ElNotification({
          title: '登录成功',
          message: `欢迎，${user.username}！`,
          type: 'success'
        })
        
        // 跳转到管理员仪表板
        router.push('/admin/dashboard')
      } catch (error: any) {
        console.error('登录失败：', error)
        ElMessage.error(error.error || '登录失败，请检查账号密码')
      } finally {
        loading.value = false
      }
    }
  })
}

// 获取验证码
const handleGetCode = async () => {
  if (!codeForm.phone) {
    ElMessage.error('请输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(codeForm.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }
  
  try {
    const code = await userApis.sendVerifyCode(codeForm.phone, 'login')
    verifyCode.value = code
    codeDialogVisible.value = true
    
    // 开始倒计时
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer)
      }
    }, 1000)
    
    ElMessage.success('验证码已生成')
  } catch (error: any) {
    console.error('获取验证码失败：', error)
    ElMessage.error(error.error || '获取验证码失败')
  }
}

// 自动填充验证码
const autoFillCode = () => {
  codeForm.code = verifyCode.value
  codeDialogVisible.value = false
  ElMessage.success('验证码已自动填充')
}

// 验证码登录
const handleCodeLogin = async () => {
  if (!codeFormRef.value) return
  
  await codeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const user = await userApis.loginByCode(codeForm.phone, codeForm.code)
        
        // 验证是否为管理员
        if (!user.is_admin) {
          ElMessage.error('该账号不是管理员，无法登录管理后台')
          return
        }
        
        // 清除倒计时
        if (countdownTimer) {
          clearInterval(countdownTimer)
        }
        
        // 保存用户信息
        userStore.update(user.id, user.username, user.phone, user.head_portrait, user.password)
        
        ElNotification({
          title: '登录成功',
          message: `欢迎，${user.username}！`,
          type: 'success'
        })
        
        // 跳转到管理员仪表板
        router.push('/admin/dashboard')
      } catch (error: any) {
        console.error('登录失败：', error)
        ElMessage.error(error.error || '登录失败，请检查验证码')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.admin-login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 450px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  font-size: 28px;
  color: #333;
  margin: 0 0 10px 0;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-form {
  margin-top: 30px;
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.login-btn:hover {
  opacity: 0.9;
}

.login-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  color: #F56C6C;
  font-size: 13px;
  margin-top: 20px;
}

.code-dialog-content {
  text-align: center;
  padding: 20px;
}

.code-number {
  font-size: 36px;
  font-weight: bold;
  color: #667eea;
  margin: 0 0 15px 0;
  letter-spacing: 5px;
}

.code-tip {
  color: #666;
  font-size: 14px;
  margin: 0;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 600;
}

:deep(.el-tabs__item.is-active) {
  color: #667eea;
}

:deep(.el-tabs__active-bar) {
  background-color: #667eea;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.el-input__wrapper:focus-within) {
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.2);
}
</style>

